import cherrypy,time,sys
from pi_comet import *
messages = []
cur = 0
class Chat:
	
	api = None
	
	@cherrypy.expose
	def index(self):
                return	open("../_html/form.html").read()
	
	@cherrypy.expose
	def get(self,index,PICometMethod=1,PICometName="",forceCache=0):
                stream = PIComet(int(PICometMethod),PICometName)
		cherrypy.response.headers['Content-type'] = stream.contentType
		
		i = int(index)
		def push(i=i):
			for j in range(0,10):
				if len(messages)==i:
					yield stream.null
				else:
					res = ""
					for message in messages[i:]:
						res += "data.push({ message:'%s', name:'%s', unixtime:'%i', cur:'%i' });"%(message["message"],message["name"],time.time(),message["time"])
						cur = message["time"]
						i+=1
                                        res+="env.index=%i;"%i
					yield stream.push(res)
				sys.stdout.flush()
				time.sleep(1)
			
		return push()
		
	get._cp_config = {'response.stream': True}
	get.exposed = True
	
	@cherrypy.expose
	def add(self,name="Guest",message=None):
		message = [str(time.time()),message][int(bool(message))]
		messages.append({ "name":name, "message":message, "time":time.time() })
		return "ok"
	add.exposed = True

if __name__ == "__main__":
	import os.path

	current_dir = os.path.dirname(os.path.abspath(__file__))
	
	conf = {
			'global':{
				'server.socket_host':'localhost',
				'server.socket_port':8080
			},
			'/pi.js':{
				'tools.staticfile.on': True,
				'tools.staticfile.filename': os.path.join(current_dir, '../_html/pi.js')
			},
			'/chat.js': {
				'tools.staticfile.on': True,
				'tools.staticfile.filename': os.path.join(current_dir, '../_html/chat.js')
			},
			'/pi.comet.js': {
				'tools.staticfile.on': True,
				'tools.staticfile.filename': os.path.join(current_dir, '../_html/pi.comet.js')
			}
	}

	cherrypy.quickstart(Chat(),'/',config=conf);
